package com.gym.core.common;

import java.util.Collections;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;

import com.google.common.collect.Lists;

public class CollectionSplitUtils {

    /**
     * 把输入的List按照输入的averageSize，分成若干个List，最后一个List的size小于等于averageSize
     * @param fromlist          原List
     * @param averageSize       每个List的size
     * @param <T>               List中元素的类型
     * @return
     */
    public static <T> List<List<T>> divideList(List<T> fromlist, int averageSize) {
    	if(CollectionUtils.isEmpty(fromlist) || averageSize <0  ){
    		return Collections.emptyList();
    	}
        List<List<T>> resultList = Lists.newArrayList();
        int totalSize = fromlist.size();
        int listCount = (int) Math.ceil(new Double(totalSize).doubleValue() / new Double(averageSize).doubleValue());
        for (int i = 0; i < listCount; i++) {
            int start = i * averageSize;
            int end;
            //最后一次分割，直接分割到最末尾
            if (i == listCount - 1) {
                end = totalSize;
            } else {
                end = start + averageSize;
            }
            List<T> subList = fromlist.subList(start, end);
            resultList.add(subList);
        }
        return resultList;
    }
}
